﻿using System.Linq;
using System.Threading.Tasks;
using System;

namespace TicTacToe.Core.Statistics
{
    partial class Database
    {
        #region internal reporting methods

        // get player id for given player or create new and add it to collection
        PlayerID GetPlayerId(Player player)
        {
            var ids = mPlayers.Where(n => n.Name == player.Name);
            if (ids.Any())
                return ids.Single();
            else
            {
                var id = new PlayerID(player.Name);
                mPlayers.Add(id);

                return id;
            }
        }

        #endregion

        // report new game
        internal void ReportNewGame(TicTacToeGame game)
        {
            if (!DatabaseManager.EnableDataCollection)
                return;

            Task.Factory.StartNew(() =>
            {
                var pid1 = GetPlayerId(game.PlayerOne);
                var pid2 = GetPlayerId(game.PlayerTwo);
                var gid = new GameID(pid1, pid2);

                mGames.Add(gid);
            });
        }

        // report game over for a game
        internal void ReportGameOver(Player winner)
        {
            if (!DatabaseManager.EnableDataCollection)
                return;

            Task.Factory.StartNew(() =>
            {
                // select game with biggest starttime
                var gid = mGames.OrderByDescending(n => n.StartTime).First();
                var pid = mPlayers.Single(n => n.Name == winner.Name);

                mWinners.Add(gid, pid);
            });
        }

        internal void ReportTurn(TicTacToeGame game, Turn turn)
        {
            if (!DatabaseManager.EnableDataCollection)
                return;

            Task.Factory.StartNew(() =>
            {
                var gid = mGames.OrderByDescending(n => n.StartTime).First();
                var pid = mPlayers.Single(n => n.Name == turn.Player.Name);
                var tid = new TurnID(gid, pid, DateTime.Now, game.CountTurns, turn.ToArray());

                mTurns.Add(tid);
            });
        }
    }
}
